//
//  MyWebViewController.m
//  OurLottery
//
//  Created by Admin on 2018/4/3.
//  Copyright © 2018年 hl. All rights reserved.
//

#import "MyWebViewController.h"
#import <WebKit/WebKit.h>

@interface MyWebViewController ()<WKUIDelegate,WKNavigationDelegate,WKScriptMessageHandler>
@property(nonatomic,strong)NSString * navTitle;
@property(nonatomic,strong)NSString * myUrl;
@property(nonatomic,retain)WKWebView * localWebView;
@end

@implementation MyWebViewController

-(instancetype)initWithTitle:(NSString *)title andUrl:(NSString * )url
{
    if (self = [super init])
    {
        self.navTitle = title;
        self.myUrl = url;
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
//    [[HUDHelper sharedInstance]syncLoading:@"正在识别二维码"];
    self.view.backgroundColor = [UIColor clearColor];
    // 设置导航栏内容
    [self setupNav];
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self getWebView];
}
/**
 *  设置导航栏内容
 */
- (void)setupNav
{
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithImage:@"avcBackIcon" highImage:@"avcBackIcon" target:self action:@selector(backClick:)];
    self.view.backgroundColor =RGBOF(0xf1f1f1);
    self.navigationItem.title = self.navTitle;
}
-(void)getWebView
{
    NSURL *myurl = [NSURL URLWithString:self.myUrl];
    
//    NSString *bundleStr = [[NSBundle mainBundle] pathForResource:@"testPhotos" ofType:@"html"];
  
//    myurl = [NSURL fileURLWithPath:URLStr];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:myurl];
    
    [self.localWebView loadRequest:request];
}

-(void)backClick:(UIControl*) control
{
    [self.navigationController popViewControllerAnimated:YES];
    [self dismissViewControllerAnimated:NO completion:nil];
}

- (void)webViewDidStartLoad:(UIWebView *)webView
{
//    [SVProgressHUD showErrorWithStatus:@"正在加载...."];
}

-(WKWebView*)localWebView{
    
    if(!_localWebView){
        WKUserContentController *userContentController = [[WKUserContentController alloc] init];
        WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
        config.userContentController = userContentController;
        if (@available (iOS 14.0,*)) {
            config.limitsNavigationsToAppBoundDomains = YES;
        }
        // 设置偏好设置 (都是默认的，需要改的时候来改)
        config.preferences = [[WKPreferences alloc] init];
        // 默认为0
        config.preferences.minimumFontSize = 10;
        // 默认认为YES
        config.preferences.javaScriptEnabled = YES;
        
        // 在iOS上默认为NO，表示不能自动通过窗口打开
        config.preferences.javaScriptCanOpenWindowsAutomatically = NO;
        _localWebView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, Main_Screen_Width, Main_Screen_Height - self.tabBarController.tabBar.frame.size.height) configuration:config];
        _localWebView.scrollView.decelerationRate = UIScrollViewDecelerationRateNormal;
        _localWebView.scrollView.bounces = NO;
        _localWebView.UIDelegate = self;
        _localWebView.navigationDelegate = self;
//        _localWebView.hidden = YES;
        [self.view insertSubview:_localWebView atIndex:0];
        _localWebView.backgroundColor = [UIColor clearColor];
        
    }
    return _localWebView;
}


- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary<NSString *,id> *)change
                       context:(void *)context
{
    if ([keyPath isEqualToString:@"title"]) {
//        if (object == self.localWebView&&[_localViewTitle isEqualToString:@"继续教育"])
//        {
//
//        }
        
    }
    
}

#pragma mark: WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
//    XL_Weak;
    if([message.name isEqualToString:@"NavigationMethod"]){//此处name为JS传出信息打包的标志<name>
        if ([message.body isEqualToString:@"showNativeNavigation"]) {
//            DeBugLog(@"show");
            dispatch_async(dispatch_get_main_queue(), ^{
//                [weakSelf showNativeNavigation];
            });
        } else if ([message.body isEqualToString:@"hideNativeNavigation"]){
//            DeBugLog(@"hide");
            dispatch_async(dispatch_get_main_queue(), ^{
//                [weakSelf hideNativeNavigation];
            });
        }
    }else if ([message.name isEqualToString:@"gotoHome"]) {//去主页
//        if(self.isPresented){
//            [self dismissViewControllerAnimated:YES completion:nil];
//        }else{
//            [self.navigationController popViewControllerAnimated:YES];
//        }
//        DeBugLog(@"去主页");
    } else if ([message.name isEqualToString:@"hideLoading"]) {//关闭加载loading
//        [self hideLoadingView];
    } else if ([message.name isEqualToString:@"changeStatusBarColor"]) {//改变状态栏颜色
        if ([message.body isEqualToString:@"1"]) {//蓝色
//            self.view.backgroundColor = [UIColor colorWithHexString:@"0x6d84a1"];
        } else {//白色
//            self.view.backgroundColor = [UIColor colorWithHexString:@"0xf8f8f8"];
        }
    }
}

- (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error{
    
}

- (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView
{
    [webView reload];
}

// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
//    _localWebView.hidden = NO;
//    UIScrollView *scroll = (UIScrollView *)self.localWebView;
//    CGRect frame = scroll.frame;
//    CGRect frame1 = scroll.frame;
//    frame.size.height = self.localWebView.scrollView.contentSize.height;
//    frame.size.width = self.localWebView.scrollView.contentSize.width;
//    scroll.frame = frame;
//
//    UIImage *tempImage = nil;
//
//    UIGraphicsBeginImageContextWithOptions(CGSizeMake(frame.size.width, frame.size.height),YES,0);
//    [scroll.layer renderInContext:UIGraphicsGetCurrentContext()];
//    tempImage = UIGraphicsGetImageFromCurrentImageContext();
//    UIGraphicsEndImageContext();
//    CGImageRef imageRef = tempImage.CGImage;
////    UIImage *finishImage = [[UIImage alloc]initWithCGImage:imageRef];
//    _localWebView.hidden = YES;
//    CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:nil options:@{ CIDetectorAccuracy : CIDetectorAccuracyHigh }];
//    NSArray *features = [detector featuresInImage:[CIImage imageWithCGImage:imageRef]];
//
//    if (features.count > 0) {
//        CIQRCodeFeature *feature = [features objectAtIndex:0];
//        NSString *scannedResult = feature.messageString;
//        DebugLog(@"%@",scannedResult);
////        [[HUDHelper sharedInstance]syncStopLoadingMessage:@"正在识别二维码"];
//
//        if (self.recogizerBlock) {
//            self.recogizerBlock(scannedResult);
//        }
//        [self dismissViewControllerAnimated:YES completion:nil];
//    }
//    else
//    {
////        [[HUDHelper sharedInstance]syncStopLoadingMessage:@"未识别到二维码"];
////        [HUDHelper alert:@"未识别到二维码"];
//    }
//
////    UIImageWriteToSavedPhotosAlbum(finishImage, nil, nil, nil);
//
//
//    scroll.frame = frame1;

//    [self hideLoadingView];
    
//    if (self.JSCacheArray.count!=0) {
//        NSString * JSString = [self.JSCacheArray objectAtIndex:0];
//        [self.localWebView evaluateJavaScript:JSString completionHandler:nil];
//        [self.JSCacheArray removeAllObjects];
//    }
    
//    dispatch_async(dispatch_get_main_queue(), ^{
//        // 注册事件
//        [self addJavaScript];
//    });
}

- (void)addJavaScript {
    XL_Weak;
    NSArray *showSendMsg = [NSArray arrayWithObjects:@"showSendMsg", nil];
    [showSendMsg enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.localWebView.configuration.userContentController removeScriptMessageHandlerForName:obj];
        });
    }];
    NSArray *NavigationMethod = [NSArray arrayWithObjects:@"NavigationMethod", nil];
    [NavigationMethod enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.localWebView.configuration.userContentController removeScriptMessageHandlerForName:obj];
        });
    }];
    
    NSArray *editCircle = [NSArray arrayWithObjects:@"editCircle", nil];
    [editCircle enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.localWebView.configuration.userContentController removeScriptMessageHandlerForName:obj];
        });
    }];
    
    NSArray *shareArticle = [NSArray arrayWithObjects:@"shareArticle", nil];
    [shareArticle enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.localWebView.configuration.userContentController removeScriptMessageHandlerForName:obj];
        });
    }];
    
    NSArray *gotoHome = [NSArray arrayWithObjects:@"gotoHome", nil];
    [gotoHome enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.localWebView.configuration.userContentController removeScriptMessageHandlerForName:obj];
        });
    }];
    
    NSArray *showimg = [NSArray arrayWithObjects:@"showimg", nil];
    [showimg enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.localWebView.configuration.userContentController removeScriptMessageHandlerForName:obj];
        });
    }];
    
    NSArray *hideLoading = [NSArray arrayWithObjects:@"hideLoading", nil];
    [hideLoading enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.localWebView.configuration.userContentController removeScriptMessageHandlerForName:obj];
        });
    }];
    
    NSArray *changeStatusBarColor = [NSArray arrayWithObjects:@"changeStatusBarColor", nil];
    [changeStatusBarColor enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.localWebView.configuration.userContentController removeScriptMessageHandlerForName:obj];
        });
    }];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.localWebView.configuration.userContentController addScriptMessageHandler:self name:@"showSendMsg"];//test
        [self.localWebView.configuration.userContentController addScriptMessageHandler:self name:@"NavigationMethod"];//隐藏导航
        [self.localWebView.configuration.userContentController addScriptMessageHandler:self name:@"editCircle"];//编辑文章
        [self.localWebView.configuration.userContentController addScriptMessageHandler:self name:@"shareArticle"];//分享
        [self.localWebView.configuration.userContentController addScriptMessageHandler:self name:@"gotoHome"];//回主页
        [self.localWebView.configuration.userContentController addScriptMessageHandler:self name:@"showimg"];//图片详情
        [self.localWebView.configuration.userContentController addScriptMessageHandler:self name:@"hideLoading"];//隐藏loading
        [self.localWebView.configuration.userContentController addScriptMessageHandler:self name:@"changeStatusBarColor"];//改变状态栏changeStatusBarColor
    });
}


@end
